const wechatcfg = require("../../cfg/wechatconfig.js")
const mongoose = require("../../cfg/dbconfig.js")
const wechattoken = require('./dbmodel.js')
const axios = require("axios")


module.exports = {
    async getAccessToken() {
        let accessToken = await wechattoken.getByName({
            "name": "accesstoken"
        })
        if (accessToken) {
            //有值，且在有效期内
            return accessToken.value
        } else {
            //过期，重新获取
            try {
                let res = await axios.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wechatcfg.wechatauth.appid + "&secret=" + wechatcfg.wechatauth.appsecret + "");
                //console.log(res)
                let time = new Date();
                await wechattoken.Save({
                    "name": "accesstoken",
                    "expireAt": time.setTime(time.getTime() + 6900 * 1000),
                    "value": res.data.access_token
                })
                return res.data.access_token
            } catch (err) {
                throw new Error("获取accesstoken出错:" + err.message)
            }
        }
    },
    //获取素材库列表
    async getMaterial(type,offset,count){
        try{
            let access_token=await this.getAccessToken()
            let res=await axios.post("https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token="+access_token,{
                type:type,
                offset:offset,
                count:count
            })
            return res.data
        }catch(err){
            throw new Error("获取素材列表时出错："+err.message)
        }
    }
}